/*
 *   Copyright 2012-present OSBI Ltd
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 */

// Packages
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import isEqual from 'react-fast-compare';
import { AppBar, Tabs, Tab, Typography } from '@material-ui/core';
import { withStyles } from '@material-ui/core/styles';

// Layout
import Container from '../../Layout/Container';

// Elements
import { BannerUpgradeLicense } from '../../Elements';

// Tabs
import { TabEnterprise, TabFeatures, TabGetHelp, TabWelcome } from './Tabs';

// Utils
import { Settings } from '../../../utils';
import muiThemeWithRoot from '../../../utils/muiThemeWithRoot';

// Styles
const styles = theme => ({
  root: {
    height: '100%',
    flexGrow: 1
  },
  skuTabLabel: {
    fontWeight: 'bold'
  },
  skuBtnEnterprise: {
    backgroundColor: theme.palette.secondary.main,
    fontWeight: 'bold'
  }
});

const TabContainer = props => {
  return <Typography component="div">{props.children}</Typography>;
};

TabContainer.propTypes = {
  children: PropTypes.node.isRequired
};

class Home extends Component {
  _isMounted = false;

  state = {
    tabValue: 0,
    isHideSplashScreen: false
  };

  componentDidMount() {
    this._isMounted = true;
    this.hideSplashScreen();
  }

  shouldComponentUpdate(nextProps, nextState) {
    return (
      !isEqual(this.props.classes, nextProps.classes) ||
      !isEqual(this.props.datasources, nextProps.datasources) ||
      !isEqual(this.props.licenseInfo, nextProps.licenseInfo) ||
      this.state.tabValue !== nextState.tabValue ||
      this.state.isHideSplashScreen !== nextState.isHideSplashScreen
    );
  }

  componentDidUpdate(prevProps, prevState) {
    const { isHideSplashScreen } = this.state;

    if (!isHideSplashScreen) {
      this.hideSplashScreen();
    }
  }

  componentWillUnmount() {
    this._isMounted = false;
    clearTimeout(this.timeout);
  }

  hideSplashScreen() {
    const $el = document.getElementById('sku-progress-indicator');
    const { datasources, licenseInfo } = this.props;

    if ($el && !datasources.loading && !licenseInfo.loading) {
      $el.classList.add('sku-available');

      this.timeout = setTimeout(() => {
        $el.setAttribute('hidden', 'hidden');
        $el.classList.remove('sku-available');

        if (this._isMounted) {
          this.setState({ isHideSplashScreen: true });
        }
      }, Settings.SPLASH_SCREEN_TIME);
    }
  }

  handleChange = (event, tabValue) => {
    this.setState({ tabValue });
  };

  render() {
    const { classes, licenseInfo } = this.props;
    const { tabValue } = this.state;

    return (
      <Container>
        <div className="content-inner no-padding-top no-padding-right no-padding-bottom">
          <div className={classes.root}>
            <AppBar color="primary" position="static">
              <Tabs
                value={tabValue}
                indicatorColor="secondary"
                onChange={this.handleChange}
                centered
              >
                <Tab className={classes.skuTabLabel} label="Welcome" />
                <Tab className={classes.skuTabLabel} label="Features" />
                <Tab className={classes.skuTabLabel} label="Get Help" />
                <Tab className={classes.skuBtnEnterprise} label="Enterprise" />
              </Tabs>
            </AppBar>
            <BannerUpgradeLicense license={licenseInfo.license} />
            {tabValue === 0 && (
              <TabContainer>
                <TabWelcome />
              </TabContainer>
            )}
            {tabValue === 1 && (
              <TabContainer>
                <TabFeatures />
              </TabContainer>
            )}
            {tabValue === 2 && (
              <TabContainer>
                <TabGetHelp />
              </TabContainer>
            )}
            {tabValue === 3 && (
              <TabContainer>
                <TabEnterprise />
              </TabContainer>
            )}
          </div>
        </div>
      </Container>
    );
  }
}

Home.propTypes = {
  classes: PropTypes.object.isRequired,
  datasources: PropTypes.object.isRequired,
  licenseInfo: PropTypes.object.isRequired
};

const mapStateToProps = state => ({
  datasources: state.datasources,
  licenseInfo: state.licenseInfo
});

export default connect(mapStateToProps)(
  muiThemeWithRoot(withStyles(styles)(Home))
);
